package com.hk.yajin.base;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;

import com.hk.developmentlib.base.DevelopmentKit;
import com.hk.developmentlib.utills.SystemUtil;
import com.hk.developmentlib.utills.constants.BroadcastConstants;
import com.hk.yajin.function.MainActivity;
import com.hk.yajin.manager.UserInfoManager;
import com.hk.yajin.model.UserInfo;
import com.hk.yajin.utills.AppUtils;
import com.hk.yajin.utills.constants.SharedPreferencesConstants;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.entity.UMessage;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;

import org.xutils.BuildConfig;
import org.xutils.common.util.LogUtil;
import org.xutils.x;

import static com.hk.yajin.base.BaseActivity.PUSH_DATA;


public class MyApplication extends Application {
    public static MyApplication mInstance;
    // public SimpleDiskCache mDiskCache;
    public static UserInfo loginUser;
    public static String loginkey;

    @Override
    public void onCreate() {
        super.onCreate();
        // CrashReport.initCrashReport(getApplicationContext(), "900055893", true);//更新版本前放开
        mInstance = this;
        initXutils();
        initUPush();
        initUShare();
        inteDevelopmentKit();
        setPushCustomHandle();
        if (inMainProcess()) {
            UserInfoManager.getInstance();
        }

    }

    private void setPushCustomHandle() {
        UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {
            @Override
            public void dealWithCustomAction(Context context, UMessage msg) {//{ {"id":33,"type":"mail"}
                if (msg != null && !TextUtils.isEmpty(msg.custom)) {
                    Intent maillIntent = new Intent(getInstance(), MainActivity.class);
                    maillIntent.putExtra(PUSH_DATA, msg.custom);
                    maillIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(maillIntent);
                }
            }
        };
        PushAgent.getInstance(this).setNotificationClickHandler(notificationClickHandler);

    }

//    private void setPushCustomHandle() {
//        UmengMessageHandler messageHandler = new UmengMessageHandler() {
//            @Override
//            public void dealWithCustomMessage(final Context context, final UMessage msg) {
//                new Handler(getMainLooper()).post(new Runnable() {
//
//                    @Override
//                    public void run() {
//                        // 对于自定义消息，PushSDK默认只统计送达。若开发者需要统计点击和忽略，则需手动调用统计方法。
//                        boolean isClickOrDismissed = true;
//                        if (isClickOrDismissed) {
//                            //自定义消息的点击统计
//                            UTrack.getInstance(getApplicationContext()).trackMsgClick(msg);
//                        } else {
//                            //自定义消息的忽略统计
//                            UTrack.getInstance(getApplicationContext()).trackMsgDismissed(msg);
//                        }
//                        Toast.makeText(context, msg.custom, Toast.LENGTH_LONG).show();
//                    }
//                });
//            }
//        };
//        PushAgent.getInstance(this).setMessageHandler(messageHandler);
//    }

    private void initUShare() {
        PlatformConfig.setWeixin("wx967daebe835fbeac", "5bb696d9ccd75a38c8a0bfe0675559b3");
        PlatformConfig.setQQZone("100424468", "c7394704798a158208a74ab60104f0ba");
        PlatformConfig.setSinaWeibo("3921700954", "04b48b094faeb16683c32669824ebdad", "http://sns.whalecloud.com");
        UMShareAPI.get(this);
    }


    private void inteDevelopmentKit() {
        DevelopmentKit.init(this);
    }


    private void initUPush() {
        PushAgent mPushAgent = PushAgent.getInstance(this);
        mPushAgent.setDebugMode(false);
        //注册推送服务，每次调用register方法都会回调该接口
        mPushAgent.register(new IUmengRegisterCallback() {

            @Override
            public void onSuccess(String deviceToken) {
                LogUtil.d("友盟推送初始化成功" + deviceToken);
            }

            @Override
            public void onFailure(String s, String s1) {
                LogUtil.e("友盟推送初始化失败" + s + s1);
            }
        });
    }

    private void initXutils() {
        x.Ext.init(this);
        x.Ext.setDebug(BuildConfig.DEBUG); // 是否输出debug日志, 开启debug会影响性能.
    }


    public boolean inMainProcess() {
        String packageName = getPackageName();
        String processName = SystemUtil.getProcessName(this);
        return packageName.equals(processName);
    }

    public static MyApplication getInstance() {
        return mInstance;
    }


    /**
     * 获取应用版本号
     *
     * @return
     */
    public String getVersionName() {
        // 获取packagemanager的实例
        PackageManager packageManager = getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = null;
        try {
            packInfo = packageManager.getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            LogUtil.e("获取不到版本号");
        }
        String version = "";
        if (packInfo != null) {
            version = packInfo.versionName;
        }
        return version;
    }

    /**
     * 清除缓存在本地的密码
     */
    protected void removePassword() {
        // 注册成功，保存用户名密码信息
        SharedPreferences sp = this.getSharedPreferences(SharedPreferencesConstants.SP_NAME_USERINFO, MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.remove("ac");
        editor.remove("pd");
        editor.commit();
    }

    /**
     * 缓存本地用户名密码
     */
    public void CachelocalUserInfo(String ac) {
        // 注册成功，保存用户名密码信息
        SharedPreferences sp = this.getSharedPreferences(SharedPreferencesConstants.SP_NAME_USERINFO, MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("ac", ac);
        editor.commit();
    }

}
